from urllib.parse import urljoin

import ddddocr
import requests
from lxml import etree

# 创建会话对象
session = requests.Session()

url = "http://127.0.0.1:8000/captcha/"
req = session.get(url)

html = etree.HTML(req.text)

# 提取 csrfmiddlewaretoken 的值
csrf_token = html.xpath("//input[@name='csrfmiddlewaretoken']/@value")[0]

img_url = html.xpath("//img[@class='captcha']/@src")[0]

full_img_url = urljoin(url, img_url)

pic = session.get(full_img_url)

with open("captcha.png", "wb") as f:
    f.write(pic.content)

ocr = ddddocr.DdddOcr()

image = open("captcha.png", "rb").read()
result = ocr.classification(image)
print(result)

data = {
    "captcha_0": html.xpath("//input[@name='captcha_0']/@value")[0],
    "captcha_1": result,
    "csrfmiddlewaretoken": csrf_token
}

# 添加请求头
headers = {
    "X-CSRFToken": csrf_token
}

req = session.post(url, data=data, headers=headers)

print(req.text)
